<?php
namespace Api\Controller;
use Think\Controller;
use Wx\Model\SendMsgModel;


/**
 * 微信支付
 */
class SalepayController extends Controller{

    /*-----------------------批发支付-start-------------------------*/
    // 选择支付方式页面
    public function choosePay(){

        $pay_id = $_GET['pay_id'];
        $pay_info = M("wholesale_pay_log")->where("id ={$pay_id}")->find();//支付订单信息
        if ($pay_info['state'] == 0){
            //获取订单信息
            $wholesale = M("wholesale")->where("pay_log_id = {$pay_id}")->group('g_u_id')->field('g_u_id')->select();//发布人分类
            foreach($wholesale as $k => $v){
                $wholesale[$k]['commodity']=M("wholesale")->where("pay_log_id = {$pay_id} AND g_u_id = {$v['g_u_id']}")->select();//获取购物车信息
                $wholesale[$k]['g_u_id'] = getMember($v['g_u_id'],'nickname,avatar');//获取发布人信息
                $wholesale[$k]['g_u_id']['farmers'] = M("member_farmers")->where("u_id = {$v['g_u_id']}")->getField('village');//获取发布人地址

                foreach($wholesale[$k]['commodity'] as $wk => $wv){
                    //获取地址信息
                    $address['name'] = $wv['name'];
                    $address['mobile'] = $wv['mobile'];
                    $address['address'] = $wv['address'];

                    //获取商品相关信息
                    $wholesale[$k]['price_all'] += ($wv['price']*$wv['num']);//获取总价
                    $wholesale[$k]['commodity'][$wk]['store_info'] = M("shop_spellgroup")->where("id = {$wv['g_id']}")->find();//获取商品信息
                    $wholesale[$k]['commodity'][$wk]['price_range'] = M('spellgroup_price_range')->where('sg_id='.$wv['g_id']." AND price = {$wv['price']}")->field("start,end")->find();// 商品批发区间
                }//end foreach
            }//end foreach

            $credit2 = M('member')->where('id='.session('u_id'))->getField('credit2');  //卡额
            $u_pass = M('member')->where('id='.session('u_id'))->getField('pay_pwd');  //用户支付密码

            //获取支付截止时间
            $deadline = M("wholesale_pay_log")->where("id = {$pay_id}")->getField('addtime');
            $deadline = strtotime(date('YmdHis',$deadline)." +1 hours")-time();
            $deadline = $deadline>0?$deadline:0;

            //支付状态更改
            if($deadline == 0){
                M("wholesale_pay_log")->where("id = {$pay_id}")->save(['state'=>2]);//已失效
                $w_info = M("wholesale")->where("pay_log_id = {$pay_id}")->field('id,g_id,num')->select();//订单id
                foreach ($w_info as $k => $v){
                    M("wholesale")->where("id = {$v['id']}")->save(['state'=>1]);//订单已失效
                    M("shop_spellgroup")->where("id = {$v['g_id']}")->setInc('num',$v['num']);//退还库存
                }//end foreach
                $this->error('支付已到截止时间',"http://www.xiangtws.com/index.php/Wx/Index/index");
            }else{
                $this->assign('pay_info',$pay_info);
                $this->assign('credit2',$credit2);
                $this->assign('u_pass',$u_pass);
                $this->assign('deadline',$deadline);
                $this->assign('address',$address);
                $this->assign('wholesale',$wholesale);
                $this->display("confirmorder-pf");
            }//end if
        }else{
            $this->error('非法进入',"http://www.xiangtws.com/index.php/Wx/Index/index");
        }//end if
    }// end fun choosePay()

    /*-----------------------批发支付-end-------------------------*/


    // 卡额支付页面
    public function cardPay(){
//        $this->ajaxReturn(session('u_id'),"JSON");return;

        if(IS_POST){
            $id = intval($_POST['id']);//所查表id
            $pass = md5(I('password'));
            $u_pass = M('member')->where('id='.session('u_id'))->getField('pay_pwd');  //卡额
            if($pass!=$u_pass){
//                $this->ajaxReturn($_POST,"JSON");
                $this->ajaxReturn(['state'=>1,'val'=>'支付密码错误'],"JSON");
            }
            $order = M($_POST['table']);
            $order_info = $order->where('id = '.$id)->find();
            if($order_info){
                // 调用支付成功后的处理
                $this->dealOrder($order_info);

                // 将用户购买的商品id放到session中；
//                $sg_id = M('shop_spellgroup_copy')->where('id='.$order_info['c_id'])->getField('sg_id');
//                session('sg_id',$sg_id);

                // 余额支付，更新
                $data = $order->where('id='.$id)->find();
                $data['card_fee'] = $order_info['total_fee'];
                $data['total_fee'] = 0.00;
                $order->save($data);
                //用户卡额减少
                //支付成功后跳转URl
                $type = substr($order_info['order_sn'], 0, 2);
                if($type == "PF"){
                    M('member')->where('id = '.session('u_id'))->setDec('credit2',$order_info['total_fee']);
                    //卡额变动记录
                    changeCredit($order_info['u_id'],$_POST['type'],'credit2','-',$order_info['total_fee']);   //增加卡额变动记录
                    sendVoice($order_info['u_id'],$_POST['type'].'共消费卡额￥'.$order_info['total_fee']);   //增加卡额变动记录
                    $this->ajaxReturn(["state"=>0,"val"=>'支付成功',"url"=>"http://www.xiangtws.com/Wx/User/stores.html"],"JSON");
                }elseif ($type == "JF"){
                    //卡额变动记录
//                    $voice = '';//推送消息
                    if($order_info['total_fee'] != 0){
                        M('member')->where('id = '.session('u_id'))->setDec('credit2',$order_info['total_fee']);//减卡额
                        changeCredit($order_info['u_id'],$_POST['type'],'credit2','-',$order_info['total_fee']);   //增加卡额变动记录
//                        $voice .= $order_info['total_fee'].'元';
                    }//end if
                    /*if($order_info['total_fee'] != 0 && $order_info['level_integral'] != 0){
                        $voice .= '+';
                    }//end if*/
                    if($order_info['level_integral'] != 0){
                        M('member')->where('id = '.session('u_id'))->setDec('credit2',$order_info['level_integral']);//减积分
                        changeCredit($order_info['u_id'],$_POST['type'],'credit1','-',$order_info['level_integral']);   //增加积分变动记录
//                        $voice .= $order_info['level_integral'].'积分';
                    }//end if
//                    sendVoice($order_info['u_id'],$_POST['type'].'共消费：'.$voice);   //增加卡额变动记录
                    $this->ajaxReturn(["state"=>0,"val"=>'支付成功',"url"=>"http://www.xiangtws.com/Wx/User/index"],"JSON");
                }//end if

            }
        }
    }


    /**
     * 批发-公众号支付 必须以get形式传递 order_id 参数,即订单id
     */
    public function wholesale_pay(){
        $order_id = intval(I('id'));
        if($order_id){
            // 获取订单信息
            $order_info = getInfo('wholesale_pay_log',array('id'=>$order_id,'u_id'=>session('u_id'),'state'=>0),'id,total_fee,u_id,order_sn');
            $order_info['openid'] = M("member")->where("id = {$order_info['u_id']}")->getField('openid');
            $order_info['order_title'] = "批发商品--支付";
            // 导入微信支付sdk
            Vendor('Weixinpay.Salepay');
            $wxpay = new \Salepay();
//            dump($order_info);
            // 获取jssdk需要用到的数据
            $data = $wxpay->getParameters($order_info);
            // 将数据分配到前台页面
            $assign = array(
                'data'=>json_encode($data)
            );
            $this->assign($assign);
            $this->display();
        }// end if
    }// end fun pay()


    /**
     * 积分兑换-公众号支付 必须以get形式传递 order_id 参数,即订单id
     */
    public function exchange_pay(){
        $order_id = intval(I('id'));
        if($order_id){
            // 获取订单信息
            $order_info = getInfo('exchange_order',array('id'=>$order_id,'u_id'=>session('u_id'),'state'=>0),'id,total_fee,u_id,order_sn');
            $order_info['openid'] = M("member")->where("id = {$order_info['u_id']}")->getField('openid');
            $order_info['order_title'] = "积分兑换商品--支付";
            // 导入微信支付sdk
            Vendor('Weixinpay.Salepay');
            $wxpay = new \Salepay();
//            dump($order_info);
            // 获取jssdk需要用到的数据
            $data = $wxpay->getParameters($order_info);
            // 将数据分配到前台页面
            $assign = array(
                'data'=>json_encode($data)
            );
            $this->assign($assign);
            $this->display();
        }// end if
    }// end fun pay()



    /**
     * notify_url接收页面，在这里写业务逻辑
    //     */
    public function notify(){
        // 导入微信支付sdk
        Vendor('Weixinpay.Salepay');
        $wxpay = new \Salepay();
        $result = $wxpay->notify();
        file_put_contents('./notify.text', $result);

        if ($result) {
            $type = substr($result['out_trade_no'], 0, 2);
            if($type == "PF"){
                $order_info = M('wholesale_pay_log')->where(array('order_sn'=>$result['out_trade_no']))->find();//支付订单信息
            }elseif ($type == "JF"){
                $order_info = M('exchange_order')->where(array('order_sn'=>$result['out_trade_no']))->find();//支付订单信息
            }//end if
            $this->dealOrder($order_info);
            echo 'SUCCESS';
        }// end if
    }// end fun notify()


    // 这里处理支付成功后的逻辑
    public function dealOrder($order_info){
        //改变支付记录状态
        $type = substr($order_info['order_sn'], 0, 2);
        if($type == "PF") {
            $pay_log = M('wholesale_pay_log')->where("id = {$order_info['id']}")->save(['paytime'=>time(),'state'=>1]);//支付成功
            if ($pay_log){
                $w_id = M("wholesale")->where("pay_log_id = {$order_info['id']}")->field('id')->select();//订单id
                foreach ($w_id as $k => $v){
                    M("wholesale")->where("id = {$v['id']}")->save(['paytime'=>time(),'state'=>2]);//订单已支付
                }//end foreach
            }//end if
        }elseif ($type == "JF"){
            $voice = '';//推送消息
            if($order_info['total_fee'] != 0){
                $voice .= $order_info['total_fee'].'元';
            }//end if
            if($order_info['total_fee'] != 0 && $order_info['level_integral'] != 0){
                $voice .= '+';
            }//end if
            if($order_info['level_integral'] != 0){
                $voice .= $order_info['level_integral'].'积分';
            }//end if
            M('exchange_order')->where("id = {$order_info['id']}")->save(['paytime'=>time(),'state'=>1]);//改变订单状态
            M("member")->where("id = {$order_info['u_id']}")->setDec('credit1',$order_info['level_integral']);//扣积分
            sendVoice($order_info['u_id'],$_POST['type'].'共消费：'.$voice);   //增加卡额变动记录
        }//end if

    }// end fun dealOrder()
}